import { login, logout, getInfo } from '@/api/user';
import { getToken, setToken, removeToken ,getUserId, setUserId, removeUserId, getUsername, setUsername, removeUsername } from '@/utils/auth.js';
import { resetRouter } from '@/router';

const getDefaultState = () => {
  return {
    token: getToken(),
    username: getUsername(),
    userId: getUserId(),
    isViewPersonInfo:false
  }
}

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
  },
  SET_USERID: (state, userId) => {
    state.userId = userId;
  },
  SET_ISVIEWPERSONINFO:(state,flag) => {
    state.isViewPersonInfo = flag;
  }
}

const actions = {
  login({ commit, state }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password }).then(response => {
        const { data } = response.data;
        commit('SET_TOKEN', data.tokenValue);
        commit('SET_USERID', data.loginId);
        commit("SET_USERNAME", username.trim());
        setToken(data.tokenValue);
        setUserId(data.loginId);
        setUsername(username.trim());
        resolve();
        actions.getInfo({commit,state});
        console.log("用户登录api",response);
      }).catch(error => {
        reject(error);
      })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if(!state.userId){
        reject(new Error("用户id异常"));
      }
      getInfo(state.userId).then(response => {
        let userInfo = null;
        if(response.data.data !== null){
          userInfo = response.data.data[0];
        } else {
          reject(new Error("获取用户信息失败"));
        }
        const { id, name, userName, age, sex, mobile, roles} = userInfo;
        commit('SET_USERNAME', userName);
        setUsername(userName);
        commit('SET_USERID', id);
        console.log('获取用户信息api',response);
        resolve(response.data.data[0].roles);
      }).catch(error => {
        reject(error);
      })
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.username).then(() => {
        removeToken(); // must remove  token  first
        removeUsername();
        removeUserId();
        resetRouter();
        commit('RESET_STATE');
        resolve();
      }).catch(error => {
        reject(error);
      })
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      removeUsername();
      removeUserId();
      commit('RESET_STATE');
      resolve();
    })
  },
  openOrClosePersonInfoDialog(state, flag){
    state.commit("SET_ISVIEWPERSONINFO",flag);
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

